package com.sskj.http


import com.sskj.http.bean.ParamBean
import com.sskj.http.bean.RequestBean
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import java.io.IOException

object Utils {

    @JvmStatic
    @Throws(IOException::class)
    fun FileInputStreamDemo(path: String): String? {
        val file = File(path)
        if (!file.exists()) {
            return null
        }
        val fis = FileInputStream(file)
        var buf = ByteArray(1024)
        val sb = StringBuffer()
        while (fis.read(buf) != -1) {
            sb.append(String(buf))
            buf = ByteArray(1024)//重新生成，避免和上次读取的数据重复
        }
        return sb.toString()
    }

    @JvmStatic
    @Throws(IOException::class)
    fun StringBufferDemo(file: File, content: String) {

        if (!file.exists())
            file.createNewFile()
        val out = FileOutputStream(file, false)
        val sb = StringBuffer()
        sb.append(content)
        out.write(sb.toString().toByteArray(charset("utf-8")))
        out.close()


    }

    fun dealMothed(requestUrl: String): String {
        val s = requestUrl.replaceFirst("/".toRegex(), "").replace("/", "_").toLowerCase()
        val chars = s.toCharArray()

        for (i in chars.indices) {
            if (chars[i] == '_') {
                chars[i + 1] = changeToUp(chars[i + 1])
            }
        }
        return String(chars).replace("_", "")
    }

    fun changeToUp(a: Char): Char {
        return (a.toInt() - 32).toChar()

    }

    fun dealModel(requestUrl: String): String {
        val s = requestUrl.replaceFirst("/".toRegex(), "").replace("/", "_").toLowerCase()
        val chars = s.toCharArray()
        chars[0] = changeToUp(chars[0])
        for (i in chars.indices) {
            if (chars[i] == '_') {
                chars[i + 1] = changeToUp(chars[i + 1])
            }
        }
        return String(chars).replace("_", "")
    }

    @JvmStatic
    fun main(args: Array<String>) {
        var request = RequestBean();
        request.getPost = true;
        request.desc = "理财账户"
        request.constantName = "FINANCE_ACCOUNT"
        request.isCreateModel = true
        request.isList = false
        request.isPageBean = false;
        request.isParseToPresenter = true
        request.methodName = "transfer"
        request.modelName = "CoinBean"
        request.isBean = false;
        request.presenterName = "BasePresenter"
        request.requestUrl = "/Home/Borrow/transfer"
        var params: MutableList<ParamBean> = mutableListOf()
        params.add(ParamBean("tpwd", "资金密码"))
        params.add(ParamBean("num", "充值数量"))
        request.paramBeans = params
        print(generatePresenter(request))
    }

    @JvmStatic
    fun generateSimplePresenter(requestBean: RequestBean): String {
        if (requestBean.isPageBean) {
            return generateFlowPresenter(requestBean)
        } else {
            return generatePresenter(requestBean)

        }
    }

    @JvmStatic
    fun generatePresenter(requestBean: RequestBean): String {

        var content = """
    /**
     * ${requestBean.desc}
     *
${getParamDescConent(requestBean.paramBeans)}
     * @return
     */
    public void ${requestBean.methodName}(${getParamStringConent(requestBean.paramBeans)}) {
        httpService.${requestBean.methodName}(${getParamConent(requestBean.paramBeans)})
                .execute(new CallBackOption<HttpData${getReturnModel(requestBean)}>() {}
                        .loadBind(mView)
                        .execute(httpData -> {
                        }));
    }
        """
        return content;

    }

    @JvmStatic
    fun generateFlowPresenter(requestBean: RequestBean): String {

        var content = """
    /**
     * ${requestBean.desc}
     *
${getParamDescConent(requestBean.paramBeans)}
     * @return
     */
    public Flowable<List<${requestBean.modelName}>>  ${requestBean.methodName}(${getParamStringConent(requestBean.paramBeans)}){
       return httpService.${requestBean.methodName}(${getParamConent(requestBean.paramBeans)})
                .converter(new JsonConverter<HttpData${getReturnModel(requestBean)}>() {
                })
                .adapt(new FlowableBody<>())
                .map(pageBeanHttpData -> pageBeanHttpData.getData().getList())
                .onErrorReturnItem(new ArrayList<>());
    }
        """
        return content;

    }

    @JvmStatic
    fun generateHttpConfig(requestBean: RequestBean): String {

        var content = """
    /**
     * ${requestBean.desc}
     */
    public static final String ${requestBean.constantName}= "${requestBean.requestUrl}";
"""
        return content;

    }

    @JvmStatic
    fun generateHttpService(requestBean: RequestBean): String {
        var isPost: Boolean = requestBean.getPost
        var methodName = requestBean.methodName
        var descName = requestBean.desc
        var constantName = requestBean.constantName
        var params: MutableList<ParamBean> = requestBean.paramBeans
        val content = """    /**
     * ${descName}
     *
${getParamDescConent(params)}     * @return
     */
     public ${getPostRequestOrGetRequestConent(isPost)}<HttpData${getReturnModel(requestBean)}> ${methodName}(${getParamStringConent(params)}) {
        return OkGo.<HttpData${getReturnModel(requestBean)}>${getPostGetConent(isPost)}(HttpConfig.BASE_URL + HttpConfig.${constantName})
${getParamRequestConent(params)}                ;
    }
        """
        return content
    }

    @JvmStatic
    fun getPostRequestOrGetRequestConent(isPost: Boolean): String {
        return if (isPost) {
            "PostRequest"
        } else {
            "GetRequest"
        }
    }

    @JvmStatic
    fun getPostGetConent(isPost: Boolean): String {
        return if (isPost) {
            "post"
        } else {
            "get"
        }
    }

    @JvmStatic
    fun getParamConent(params: MutableList<ParamBean>): String {
        var content: String = ""
        params.forEach { content = content + "," + it.value }
        content = content.replaceFirst(",", "");
        return content;
    }

    @JvmStatic
    fun getParamStringConent(params: MutableList<ParamBean>): String {
        var content: String = ""
        params.forEach { content = content + ",String " + it.value }
        content = content.replaceFirst(",", "");
        return content;
    }

    @JvmStatic
    fun getParamRequestConent(params: MutableList<ParamBean>): String {
        var content: String = ""
        params.forEach {
            content = content + """                .params("${it.value}", ${it.value})
                |
            """.trimMargin()
        }
        return content;
    }

    @JvmStatic
    fun getParamDescConent(params: MutableList<ParamBean>): String {
        var content: String = ""
        params.forEach {
            content = content + """     * @param ${it.value} ${it.desc}
"""
        }
        return content;
    }

    @JvmStatic
    fun getReturnModel(request: RequestBean): String {
        if (request.isBean) {
            if (request.isList) {
                return """<List<${request.modelName}>>"""
            } else if (request.isPageBean) {
                return """<PageBean<${request.modelName}>>"""
            } else {
                return """<${request.modelName}>"""
            }
        } else {
            return ""
        }
    }

    @JvmStatic
    fun generateBean(request: RequestBean): String {
        var content="""
package ${FileUtil.projectPackge}.bean;

public class ${request.modelName} {

}

        """.trimIndent()
        return content;
    }


}
